package com.gexin.service.user;

import com.gexin.common.cache.CacheUtils;
import com.gexin.common.model.ApiResponse;
import com.gexin.common.utils.IdGenerateUtils;
import com.gexin.common.utils.OtherUtil;
import com.gexin.common.utils.SendTemplateMessage;
import com.gexin.common.utils.StringUtil;
import com.gexin.controller.commom.WeixinTransfer.WeixinTransferUtil;
import com.gexin.controller.commom.WeixinTransfer.model.WeixinTransferResult;
import com.gexin.model.CommentZan;
import com.gexin.model.activity.MemberInfo;
import com.gexin.model.integral.UserIntegralRecord;
import com.gexin.model.notice.NoticeNews;
import com.gexin.model.notice.NoticeNewsComment;
import com.gexin.model.notice.NoticeZan;
import com.gexin.model.order.Order;
import com.gexin.model.system.AdminConfig;
import com.gexin.model.user.UserCheckIn;
import com.gexin.model.user.UserRebate;
import com.gexin.model.weixin.UserAddress;
import com.gexin.model.weixin.WeixinAppConfig;
import com.gexin.model.weixin.WeixinUser;
import com.gexin.service.conpon.CouponService;
import com.jfinal.plugin.activerecord.Page;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.gexin.model.user.UserRebate.*;

public class UserService {
	public static UserService dao = new UserService();

	/**
	 * 保存用户收货地址
	 * @param address 地址信息
	 * @param authUser
	 */
	public ApiResponse saveAddress(UserAddress address , WeixinUser authUser) {
		if(address==null)
			return new ApiResponse(false,"地址信息错误!");
		if(address.getCityId()==null)
			return new ApiResponse(false,"所属城市不能为空!");
		if(address.getCountyId()==null)
			return new ApiResponse(false,"收货区域不能为空!");
		if (StringUtil.isBlank(address.getConsignee()))
			return new ApiResponse(false,"收货人信息不能为空!");
		if (StringUtil.isBlank(address.getPhone()))
			return new ApiResponse(false,"收货人电话不能为空!");
		if(StringUtil.isBlank(address.getAddress()))
			return new ApiResponse( false, "收货人详细信息不能为空!");
		ApiResponse apiResponse ;
		if(address.getId()==null){
			address.setUserId(authUser.getId());
			address.setCreateTime(new Date());
			boolean save = address.save();
			if(authUser.getCityId()==null){
				authUser.setAreaId(address.getCountyId().toString());
				authUser.setCityId(address.getCityId().toString());
				authUser.update();
			}
			apiResponse = new ApiResponse(save,save?"保存成功!":"保存失败!");
		}else{
			boolean update = address.update();
			apiResponse = new ApiResponse(update,update?"修改成功!":"修改失败!");
		}
		return apiResponse;
	}

	public UserAddress findUserAddressInfoById(String addressId) {
		return UserAddress.dao.findById(addressId);
	}

	public ApiResponse deleteUserAddressById(String addressId) {
		//查询是否有订单使用该地址
		Order byAddress = Order.dao.findByAddress(addressId);
		if(byAddress!=null){
			return new ApiResponse(false,"该地址已被订单使用!");
		}
		boolean delete = UserAddress.dao.deleteById(addressId);

		return new ApiResponse(delete,delete?"删除成功!":"删除失败!");
	}

	/**
	 * 根据用户id获取用户的所有收货地址
	 * @param
	 */
	public List<UserAddress> findUserAddressListByUserId(Integer userId) {
		return UserAddress.dao.findByUserAll(userId);
	}


	public ApiResponse singIn(WeixinUser authUser) {
		ApiResponse apiResponse = new ApiResponse(false,"签到失败!");
		Object o = CacheUtils.get("sinIn:" + authUser.getId());
		if(o==null){
			boolean save =false;
			UserCheckIn userCheckIn = UserCheckIn.dao.findById(authUser.getId());
			if (userCheckIn==null){
				userCheckIn = new UserCheckIn();
				userCheckIn.setIscheckin(true);
				userCheckIn.setCheckinNum(1);
				userCheckIn.setUserId(authUser.getId());
				save = userCheckIn.save();
			}else{
				userCheckIn.setCheckinNum(userCheckIn.getCheckinNum()+1);
				save =userCheckIn.update();
			}
			if(save){
				AdminConfig config = AdminConfig.dao.getSysConfig();
				Integer integral = config.getSignInIntegral();
				if(integral==null){
					integral = 15;
				}
				UserIntegralRecord.dao.saveLog(integral,UserIntegralRecord.TYPEADD,"签到添加积分",authUser.getId());
				Integer sumIntegral = authUser.getSumIntegral();
				if(sumIntegral==null)
					sumIntegral=0;
				authUser.setSumIntegral(sumIntegral+integral);
				authUser.update();

				Integer userId = authUser.getId();
				MemberInfo memberInfo = MemberInfo.dao.findFirst("select * from t_member_info where user_id"+userId);
//				config.get
//				memberInfo.setIntegral();
			}
			CacheUtils.set("sinIn:"+authUser.getId(),authUser.getId(),OtherUtil.getSecondsNextEarlyMorning().intValue());
			apiResponse = new ApiResponse(save,save?"签到成功!":"签到失败!");
		}else{
			apiResponse = new ApiResponse(false,"今日已经签到");

		}
		return apiResponse;
	}

	public List<NoticeNewsComment> myComment(WeixinUser authUser) {
		List<NoticeNewsComment> comments = NoticeNewsComment.dao.findByUserId(authUser);
		return comments;
	}

	/**
	 * 用户点赞
	 * @param commentId
	 * @param user
	 */
	public ApiResponse commentZan(String commentId , WeixinUser user) {
		NoticeNewsComment comment = NoticeNewsComment.dao.findById(commentId);
		if(comment==null){
			return new ApiResponse(false,"评论不存在!");
		}
		CommentZan commentZans = CommentZan.dao.findByUserAndCommentId(user.getId() , commentId);
		Integer likeCount = comment.getLikeCount();
		if(likeCount==null){
			likeCount=0;
		}
		ApiResponse apiResponse = new ApiResponse();
		if(commentZans!=null){
			commentZans.delete();
			comment.getLikeCount();
			comment.setLikeCount(likeCount-1);
			boolean update = comment.update();
			apiResponse = new ApiResponse(update,update?"取消成功!":"取消失败!");
		}else{
			comment.setLikeCount(likeCount+1);
			comment.update();
			commentZans = new CommentZan();
			commentZans.setCommentId(comment.getId());
			commentZans.setZanUser(user.getId());
			commentZans.setCreateTime(new Date());
			boolean save = commentZans.save();
			apiResponse = new ApiResponse(save,save?"点赞成功!":"点赞失败!");
		}

		return apiResponse;
	}


	/**
	 * 用户领取优惠券
	 * @param couponId 优惠券id
	 * @param authUser 当前登录用户
	 */
	public ApiResponse receiveCoupon(String couponId , WeixinUser authUser) {
		return CouponService.dao.receiveCoupon(couponId,authUser);
	}

	public ApiResponse noticeZan(String noticeId , WeixinUser user) {
		NoticeNews noticeNews = NoticeNews.dao.findById(noticeId);
		if(noticeNews==null){
			return new ApiResponse(false,"资讯不存在!");
		}
		NoticeZan noticeZans = NoticeZan.dao.findByUserAndCommentId(user.getId() , noticeId);
		Integer zanCount = noticeNews.getZanCount();
		if(zanCount==null){
			zanCount=0;
		}
		ApiResponse apiResponse = new ApiResponse();
		if(noticeZans!=null){
			noticeZans.delete();
			noticeNews.setZanCount(zanCount-1);
			boolean update = noticeNews.update();
			apiResponse = new ApiResponse(update,update?"取消成功!":"取消失败!");
		}else{
			noticeNews.setZanCount(zanCount+1);
			noticeNews.update();
			noticeZans = new NoticeZan();
			noticeZans.setNoticeId(noticeNews.getId());
			noticeZans.setUserId(user.getId());
			noticeZans.setCreateTime(new Date());
			boolean save = noticeZans.save();
			apiResponse = new ApiResponse(save,save?"点赞成功!":"点赞失败!");
		}
		return apiResponse;
	}

	public Page<UserIntegralRecord> findIntegralList(Integer page, Integer pageSize, WeixinUser authUser) {
		UserIntegralRecord record = new UserIntegralRecord();
		record.setUserId(authUser.getId());
		return UserIntegralRecord.dao.query(page,pageSize,record);
	}

	public ApiResponse changeDefaultAdd(String addressId) {
		if(StringUtil.isBlank(addressId)){
			return new ApiResponse(false,"收货地址id不能为空!");
		}
		UserAddress userAddress = UserAddress.dao.findById(addressId);
		if(userAddress==null){
			return  new ApiResponse(false,"收货地址不存在!");
		}
		UserAddress.dao.setNotDefaultAll(userAddress.getUserId());
		Integer isDefault = userAddress.getIsDefault();
		if (isDefault==null){
			isDefault = 0;
		}
		userAddress.setIsDefault(isDefault==UserAddress.DEFAULT_FALSE?UserAddress.DEFAULT_TRUE:UserAddress.DEFAULT_FALSE);
		boolean update = userAddress.update();
		return new ApiResponse(update,update?"操作成功!":"操作失败!");
	}

	/**
	 * 添加用户返利
	 * @param userId
	 */
	public ApiResponse addUserRebate(Integer userId,String orderId) {
		WeixinUser user = WeixinUser.dao.findById(userId);
		Integer extensionUserId = user.getExtensionUserId();
		WeixinUser extensionUser = WeixinUser.dao.findById(extensionUserId);
		if(extensionUser!=null&&(extensionUser.getIsAgent()==null||(extensionUser.getIsAgent()!=null&&extensionUser.getIsAgent()!=1))){
			BigDecimal price = new BigDecimal(0);
			BigDecimal accountBalance = extensionUser.getAccountBalance();
			Integer number = extensionUser.getEarningsNumber();
			if(number==null){
				number=1;
			}
			switch (number){
				case 1:
					price = new BigDecimal(5);
					number +=1;
					break;
				case 2:
					price = new BigDecimal(6);
					number +=1;
					break;
				case 3:
					number = 1;
					price = new BigDecimal(8);
					break;
			}
			accountBalance = accountBalance.add(price);
			extensionUser.setAccountBalance(accountBalance);
			extensionUser.setEarningsNumber(number);

			UserRebate userRebate = new UserRebate();
			userRebate.setCreateTime(new Date());
			userRebate.setPrice(price);
			userRebate.setShareOne(user.getId());
			userRebate.setStatus(STATUS_SHOURU);
			userRebate.setUserId(extensionUser.getId());
			userRebate.setRemark("用户收入");
			userRebate.setOrderId(orderId);
			userRebate.setId(IdGenerateUtils.getId());
			boolean save = userRebate.save();

			if(save){
				Map<String, String> map = new HashMap<>();
				String first = "您好,你的返利已到帐!";
				map.put("first",first);
				map.put("keyword1",price.toString());
				map.put("keyword2",new SimpleDateFormat("yyyy年MM月DD日 hh:mm").format(userRebate.getCreateTime()));
				map.put("remark","感谢你的参与!");
				new SendTemplateMessage().sendTemplate(SendTemplateMessage.FANLI , user.getOpenid() , map);

			}


			return new ApiResponse(save,save?"成功!":"失败!");
		}
		return null;
	}

	/**
	 * 用户提现
	 * @param authUser
	 * @param price
	 */
	public ApiResponse withdrawal(WeixinUser authUser, String priceStr) {
		if (authUser==null){
			return new ApiResponse( false,"用户未登录!");
		}
//		if(authUser.getAccountBalance()==null||authUser.getAccountBalance().compareTo(new BigDecimal(0.00))!=1){
//			return  new ApiResponse(false,"用户余额不足!");
//		}
		if(StringUtil.isBlank(priceStr)){
			return new ApiResponse(false,"提现金额不能为空!！");
		}
		BigDecimal price = new BigDecimal(0.0);
		try{
			price = new BigDecimal(priceStr);
		}catch (NumberFormatException e){
			return new ApiResponse(false,"数据格式错误！");
		}

		BigDecimal accountBalance = authUser.getAccountBalance();
		if(price.compareTo(accountBalance)!=0){
			return new ApiResponse(false,"提现必须整体提现");
		}

		authUser.setAccountBalance(new BigDecimal(0));
		authUser.setIceAccount(authUser.getIceAccount().add(accountBalance));
		authUser.update();
		UserRebate userRebate = new UserRebate();
		userRebate.setUserId(authUser.getId());
		userRebate.setId(IdGenerateUtils.getId());
		userRebate.setStatus(STATUS_TIXIAN);
		userRebate.setPrice(accountBalance);
		userRebate.setCreateTime(new Date());
		userRebate.setRemark("用户提现!");
		userRebate.setState(STATE_SQ);
		userRebate.save();
		WeixinAppConfig weixinAppConfig = WeixinAppConfig.dao.findById(2);
//		KusyUtil.Api_key, KusyUtil.Sign_Key  WXMchid
		WeixinTransferResult transfer = WeixinTransferUtil.transfer(
				weixinAppConfig.getAppId(),
				weixinAppConfig.getWxKey(),
				weixinAppConfig.getWxMchid(),
				weixinAppConfig.getKeystoreFilePath(),
				authUser.getOpenid(),
				userRebate.getId(),
				authUser.getNickname(),
				userRebate.getPrice(),
				"用户提现");
		if(transfer.isState()){
			userRebate.setState(STATE_CQ);
			boolean update = userRebate.update();
				if(update){
					Map<String, String> map = new HashMap<>();
					String first = "您的提现已到微信账号余额，请注意查收";
					map.put("first",first);
					map.put("keyword1",price.toString());
					map.put("keyword2",new SimpleDateFormat("yyyy年MM月DD日 hh:mm").format(userRebate.getCreateTime()));
					map.put("keyword3",new SimpleDateFormat("yyyy年MM月DD日 hh:mm").format(userRebate.getCreateTime()));
					map.put("remark","点击查看");
					new SendTemplateMessage().sendTemplate(SendTemplateMessage.FANLI , authUser.getOpenid() , map);
				}


		}else{
			userRebate.setState(STATE_SB);
			authUser.setAccountBalance( userRebate.getPrice());
			authUser.setIceAccount(authUser.getIceAccount().subtract( userRebate.getPrice()));
			authUser.update();
		}
		return new ApiResponse(transfer.isState(),transfer.getReturn_msg());
	}

	public Page<UserRebate> findUserRebate(WeixinUser authUser, Integer page, Integer pageSize, Integer state) {
		return UserRebate.dao.findPageList(page,pageSize,authUser,state);
	}
}
